package com.ng.biz.controller;

import java.util.Date;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.jfinal.kit.StrKit;
import com.jfinal.plugin.activerecord.Page;
import com.ng.biz.model.domain.DataTask;
import com.ng.biz.model.request.DataTaskStartStopRequest;
import com.ng.common.annotation.TokenRequired;
import com.ng.common.annotation.Tx;
import com.ng.common.controller.Controller;
import com.ng.common.model.response.R;
import com.ng.common.timer.DataTaskTimer;
import com.ng.common.util.UuidUtil;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.Parameters;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.servlet.http.HttpServletRequest;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;

@Tag(name = "数据抽取任务管理")
@RequiredArgsConstructor
@RestController
@RequestMapping("/biz/data/task")
@Slf4j
public class DataTaskController extends Controller {
	
	@Autowired
	private DataTaskTimer dataTaskTimer;
	
	
    @Operation(summary = "分页获取数据任务列表")
    @Parameters({
        @Parameter(name = "keywords", description = "关键字", required = false),
        @Parameter(name = "cur", description = "当前页码", required = true),
        @Parameter(name = "limit", description = "每页数据量", required = true)
    })
    @TokenRequired
    @GetMapping("/pages")
    public R<Page<DataTask>> pages(
        HttpServletRequest request,
        @RequestParam(name = "keywords", required = false, defaultValue = "") String keywords,
        @RequestParam(name = "cur", required = false, defaultValue = "1") int cur,
        @RequestParam(name = "limit", required = false, defaultValue = "10") int limit
    ) throws Exception {
        String sqlExceptSelect = " from " + DataTask.TABLE_NAME + " a WHERE 1=1 ";
        if (!StrKit.isBlank(keywords)) {
            sqlExceptSelect += " and (a.name like '%" + keywords + "%' ) ";
        }
        sqlExceptSelect += " ORDER BY a.last_time desc ";
        Page<DataTask> page= DataTask.dao.paginate(cur, limit, "select a.* ", sqlExceptSelect);
        for(DataTask dataTask:page.getList()) {
        	dataTask.setIsRunning(dataTaskTimer.isRunning(dataTask.getId())?"1":"0");
        }
        return R.ok(page);
    }

    @Operation(summary = "保存数据任务")
    @Parameters({
        @Parameter(name = "dataTask", description = "数据任务对象", required = true)
    })
    @TokenRequired
    @Tx
    @PostMapping("/save")
    public R<DataTask> save(HttpServletRequest request, @RequestBody DataTask dataTask) {
        try {
            // 验证必填字段
            if (StrKit.isBlank(dataTask.getName())) {
                return R.failed("任务名称不能为空");
            }
            
            if (StrKit.isBlank(dataTask.getInput())) {
                return R.failed("输入配置不能为空");
            }

            if (StrKit.isBlank(dataTask.getContent())) {
                return R.failed("内容配置不能为空");
            }

            if (StrKit.isBlank(dataTask.getStandardFields())) {
                return R.failed("字段定义不能为空");
            }

            if (StrKit.isBlank(dataTask.getOutput())) {
                return R.failed("输出配置不能为空");
            }

            if (StrKit.notBlank(dataTask.getId())) {
                // 更新
                dataTask.setUpdateUserId(getUserId(request));
                dataTask.setUpdateTime(new Date(System.currentTimeMillis()));
                if (dataTask.update()) {
                    return R.ok(dataTask);
                } else {
                    return R.failed("更新失败");
                }
            } else {
                // 新增
                dataTask.setId(UuidUtil.getUUID());
                dataTask.setCreateUserId(getUserId(request));
                dataTask.setCreateTime(new Date(System.currentTimeMillis()));
                if (dataTask.save()) {
                    return R.ok(dataTask);
                } else {
                    return R.failed("保存失败");
                }
            }
        } catch (Exception e) {
            log.error("保存数据任务失败", e);
            return R.failed(e.getMessage());
        }
    }

    @Operation(summary = "删除数据任务")
    @Parameters({
        @Parameter(name = "ids", description = "数据任务ID集合(逗号分隔)", required = true)
    })
    @DeleteMapping("/{ids}")
    @TokenRequired
    public R<String> delete(@PathVariable("ids") String ids) {
        if (StrKit.isBlank(ids)) {
            return R.failed("请选择需要删除的任务");
        }
        String[] idArray = ids.split(",");
        for (String id : idArray) {
            DataTask.dao.deleteById(id);
            dataTaskTimer.stopTask(id);
        }
        return R.ok("删除成功");
    }

    @Operation(summary = "启停任务")
    @Parameters({
        @Parameter(name = "id", description = "任务ID", required = true),
        @Parameter(name = "request", description = "启停请求", required = true)
    })
    @TokenRequired
    @PostMapping("/{id}/status")
    public R<String> updateStatus(
        @PathVariable("id") String id, 
        @RequestBody DataTaskStartStopRequest request
    ) {
        try {
            if(request.isStatus()) {
                if(dataTaskTimer.isRunning(id)) {
                    return R.failed("数据任务已启动，本次操作无效.");
                }
                return dataTaskTimer.startTask(id);
            }else {
                if(!dataTaskTimer.isRunning(id)) {
                    return R.failed("数据任务已未启动，本次操作无效.");
                }
                dataTaskTimer.stopTask(id);
                return R.ok();
            }
        } catch (Exception e) {
            log.error("启停任务:{}", e);
            return R.failed(e.getMessage());
        }
    }

    @Operation(summary = "获取任务执行状态")
    @Parameters({
        @Parameter(name = "id", description = "任务ID", required = true)
    })
    @TokenRequired
    @GetMapping("/{id}/execution-status")
    public R<Boolean> getTaskExecutionStatus(@PathVariable("id") String id) {
        try {
            return R.ok(dataTaskTimer.getTaskExecutionStatus(id));
        } catch (Exception e) {
            log.error("获取任务执行状态失败:{}", e);
            return R.failed(e.getMessage());
        }
    }
}
